import { createRouter, createWebHistory, RouteRecordRaw,createWebHashHistory } from 'vue-router'
import { getToken, setToken, removeToken } from '@/utils/auth'

const routes: Array<RouteRecordRaw> = [{
    path: "/",
    redirect: "/login",
}, {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login.vue'),

}, {
    path: '/home',
    name: 'Home',
    component: () => import('../views/home.vue'),
}, {
    path: '/agreement',
    name: 'Agreement',
    component: () => import('../components/agreement/agreement.vue'),
}]

const router = createRouter({
  // history: createWebHistory(import.meta.env.BASE_URL),
  history: createWebHashHistory(),
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  let hrefIdx = window.location.href.indexOf('access_token=');
  if (to.path === '/login') {
    return next()
  } else {
    if (hrefIdx > -1) { // 如果url携带token,并且没有登录后的用户信息
      // 截取token
      let arr = window.location.href.split('&') //避免有多个传参
      let tokenArr = arr.filter(_ => _.includes('access_token=')) //筛选出含有token的数组
      let access_token = tokenArr[0].split('access_token=')[1]  //拿到token
      setToken(access_token)
      next();
    } else {
      if (getToken() == null && getToken() == '' && getToken() == undefined) {
        return next('/login') // 不存在token
      } else {
        // 存在token，直接放行
        next()
      }
    }
  }
})

export default router
